<template>
  <div class="w1">
    <h1>发布文章</h1>
    <form @submit.prevent = "submit">
      <div class="profile">
        <span>文章标题：</span>
        <input type="text" class="title" v-model.trim="title"><br><br>
        <span>封面&摘要：</span>
         <!-- <div style="display:inline-block">
          <em>+</em>
          <p>优质的封面有利于推荐</p>
        </div> -->
        <el-upload
          action="#"
          ref="pictureUpload" 
          list-type="picture-card"
          :auto-upload="false"
          :limit="2"
          style="margin-left:100px">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
        </el-upload>
        <p>优质的封面有利于推荐</p>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <span>内容摘要：</span>
        <el-input class="text" type="textarea"
                  v-model.lazy="synopsis" 
                  maxlength="50" 
                  :autosize="{ minRows: 5}"
                  show-word-limit 
                  placeholder="摘要（必填）：会在推荐、列表邓场景外露，帮助读者快速了解内容"/><br><br>
        <span>文章标签：</span>
        <el-tag
          :key="tag"
          v-for="tag in tags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button><br><br>
        <span>文章分类：</span>
        <select v-model="classify">
          <option value="c">c语言</option>
          <option value="qianduan">前端学习</option>
          <option value="jihua">学习计划</option>
          <option value="shiyong">实用技术</option>
          <option value="kaifa">开发基础</option>
          <option value="hexin">微服务核心</option>
          <option value="lishi">日本历史</option>
          <option value="yinyue">日本流行音乐史</option>
        </select><br><br>
        <!-- <span>内容类型：</span>
        <input type="radio" name="kind" value="original" v-model="articleInfo.kind"><span>原创</span>
        <input type="radio" name="kind" value="reprint" v-model="articleInfo.kind"><span>转载</span>
        <input type="radio" name="kind" value="translate" v-model="articleInfo.kind"><span>翻译</span><br><br> -->
        <span>发表日期：</span>
        <span>{{ dateFormat(newDate) }}</span>
      </div>
      <div style="width: 840px; margin: auto;">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 800px; overflow-y: hidden;"
            v-model="html"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
        />
    </div>
      <button class="btn">提交</button>
    </form>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {upImg ,upArticle} from '@/api/index'

export default {
    name:'Publish',
    components: { Editor, Toolbar },
    data(){
      return{
          title:'',
          // cover:'',
          synopsis:'',
          // label:'',
          classify:'',
          // kind:'',
          tags:[ '学习'],
        newDate: new Date(),
        timer:null,
        
        inputVisible: false,
        inputValue: '',
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,

        editor: null,//实例
        html: '测试默认内容',//默认的内容
        toolbarConfig: { 
          excludeKeys: ["fullScreen"],
        },
        editorConfig: { 
          placeholder: '请输入内容...',
          MENU_CONF: {
                //配置上传图片
                uploadImage: {
                    customUpload: this.uploadImg
                },
                // 配置插入图片
                insertImage: {
                  // 插入图片的回调
                  onInsertedImage: this.onInsertedImage
                }
            }
        },
        mode: 'default', // or 'simple'
        allImage:[],
        alreadyDeleteImg:[]
      }
    },
    mounted(){
        // const editor = new E("#box");
        // editor.config.onchange = (newHtml) =>{
        //   this.editorData = newHtml;
        // };
        // editor.create();
        // this.texttxt = editor;

        this.timer = setInterval(() => {
          this.newDate = new Date(); // 修改数据date
        }, 1000)
    },
    methods:{
      onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      },
       //上传图片
       uploadImg(file, insertFn){
            let imgData = new FormData();
            imgData.append("file", file);
                  console.log("文件：",file)
                    //调接口，上传图片
                    
                  upImg(imgData).then(response => {
                    console.log(response)
                      if(response.status == 0){
                          insertFn(response.url);
                      }else{
                          this.$message.error("图片上传错误,请重新上传！")
                      }
                  })
        },
        onInsertedImage(imageNode) { 
            // imageNode是一个图片对象
            console.log("插入图片之后的回调:",imageNode)
            this.allImage == this.allImage.push(imageNode)
        },
      dateFormat(time) {
      let date = new Date(time);
      let year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
      * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
      * */
      let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      // 拼接
      return year + "-" + month + "-" + day  
    },
    submit(){
      // const{articleInfo} = this
      upArticle(this.title,this.classify,this.synopsis,this.tags,this.html,this.dateFormat(this.newDate)).then(response =>{
        console.log(this.title,this.classify,this.synopsis,this.tags,this.html,this.dateFormat(this.newDate))
        if(response.data.isupload){
          console.log('ok')
        }
      } )
      // console.log(this.title,this.classify,this.synopsis,this.tags,this.html,this.dateFormat(this.newDate))
      // // console.log(JSON.stringify(this.articleInfo))
      // console.log(this.userInfo)
      // console.log(this.texttxt.txt.html())
      // this.$router.push('/classify/c/Cdetail1')
      console.log(this.editor.getHtml())
    },
     handleClose(tag) {
        this.tags.splice(this.tags.indexOf(tag), 1);
      },
    showInput() {
      if(this.tags.length < 3){
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      }
    },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.tags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
       handleRemove(file) {
        let uploadFiles = this.$refs.pictureUpload.uploadFiles
        for (var i = 0; i < uploadFiles.length; i++) {
          if (uploadFiles[i]['url'] == file.url) {
            uploadFiles.splice(i, 1)
          }
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleDownload(file) {
        window.open(file.url)
      }
  },
  // mounted(){
  //   // 模拟 ajax 请求，异步渲染编辑器
  //       setTimeout(() => {
  //           this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
  //       }, 1500)
  //   },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
    }
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>

<style scoped>
.w1 {
  /* width: 1150px; */
  /* margin: 0 auto; */
  padding-top: 80px;
  /* height:2700px; */
  background-color: #f5f6f7;
}
  h1{
    margin-left: 380px;
  }
  .profile{
    /* border: 1px solid gray; */
    width: 840px;
    height: 620px;
    margin: 20px auto;
    padding: 30px 0 0 50px;
    background-color: #ffffff;
    border-radius: 1%;
    color:#737579;
  }
  .title{
    border-bottom: 1px solid gray;
  }
  .profile span{
    font-size: 15px;
  }
  .profile input{
    font-size: 20px;
    margin: 0 5px 0 20px
  }
  em{
    display: inline-block;
    border: 1px dashed #d9d9d9;
    width: 170px;
    height: 100px;
    margin:20px 20px 5px 70px;
    line-height: 100px;
    text-align: center;
    font-size: 40px;
    color: #8e8e8e;
  }
  .profile .text{
    width: 400px;
    height: 115px;
    /* border: 1px solid #e9ebef; */
    /* margin:  -140px 0 0 50px; */
    font-size: 14px;
  }
  .profile p{
    margin: 5px 0 15px 110px;
    color: gray;
  }
  select{
    background-color: white;
    height: 26px;
  }
  #box{
    z-index: 1;
    width: 850px;
    height: 700px;
    margin: 0 auto;
    background-color: #ffffff;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .btn{
    position: absolute;
    width: 80px;
    height: 40px;
    font-size: 16px;
    right: 260px;
    bottom: -946px;
  }
</style>